package com.epapyrus.plugpdf;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/*
The MIT License (MIT)

Copyright (c) 2014 Jesper Borgstrup

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class HSVColorWheel  extends View {

    private static final float FADE_OUT_FRACTION = 0.03f;

    private static final int POINTER_LINE_WIDTH_DP = 2;
    private static final int POINTER_LENGTH_DP = 10;

    private final Context context;

    private OnColorSelectedListener listener;
    public HSVColorWheel(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        init();
    }

    public HSVColorWheel(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public HSVColorWheel(Context context) {
        super(context);
        this.context = context;
        init();
    }

    private int pointerLength;
    private int innerPadding;
    private Paint pointerPaint = new Paint();
    private void init() {
        float density = context.getResources().getDisplayMetrics().density;
        pointerLength = (int) (density * POINTER_LENGTH_DP );
        pointerPaint.setStrokeWidth(  (int) (density * POINTER_LINE_WIDTH_DP ) );
        innerPadding = pointerLength / 2;
    }

    public void setListener( OnColorSelectedListener listener ) {
        this.listener = listener;
    }

    float[] colorHsv = { 0f, 0f, 1f };
    public void setColor( int color ) {
        Color.colorToHSV(color, colorHsv);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if ( bitmap != null ) {
            canvas.drawBitmap(bitmap, null, rect, null);
            float hueInPiInterval = colorHsv[0] / 180f * (float)Math.PI;

            selectedPoint.x = rect.left + (int) (-Math.cos( hueInPiInterval ) * colorHsv[1] * innerCircleRadius + fullCircleRadius);
            selectedPoint.y = rect.top + (int) (-Math.sin( hueInPiInterval ) * colorHsv[1] * innerCircleRadius + fullCircleRadius);

            canvas.drawLine( selectedPoint.x - pointerLength, selectedPoint.y, selectedPoint.x + pointerLength, selectedPoint.y, pointerPaint );
            canvas.drawLine( selectedPoint.x, selectedPoint.y - pointerLength, selectedPoint.x, selectedPoint.y + pointerLength, pointerPaint );
        }
    }

    private Rect rect;
    private Bitmap bitmap;

    private float innerCircleRadius;
    private float fullCircleRadius;


    private Point selectedPoint = new Point();

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        rect = new Rect( innerPadding, innerPadding, w - innerPadding, h - innerPadding );
        bitmap = Bitmap.createBitmap( w - 2 * innerPadding, h - 2 * innerPadding, Config.ARGB_8888 );

        fullCircleRadius = Math.min( rect.width(), rect.height() ) / 2;
        innerCircleRadius = fullCircleRadius * ( 1 - FADE_OUT_FRACTION );

        createBitmap();
    }

    private void createBitmap() {
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.colorpicker);
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int maxWidth = MeasureSpec.getSize( widthMeasureSpec );
        int maxHeight = MeasureSpec.getSize( heightMeasureSpec );

        int width, height;
        /*
         * Make the view quadratic, with height and width equal and as large as possible
         */
        width = height = Math.min( maxWidth, maxHeight );

        setMeasuredDimension( width, height );
    }

    public int getColorForPoint( int x, int y, float[] hsv ) {
        x -= fullCircleRadius;
        y -= fullCircleRadius;
        double centerDist = Math.sqrt( x*x + y*y );
        hsv[ 0 ] = (float) (Math.atan2( y, x ) / Math.PI * 180f) + 180;
        hsv[ 1 ] = Math.max( 0f, Math.min( 1f, (float) (centerDist / innerCircleRadius) ) );
        return Color.HSVToColor( hsv );
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getActionMasked();
        switch ( action ) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                if ( listener != null ) {
                    listener.colorSelected( getColorForPoint( (int)event.getX(), (int)event.getY(), colorHsv ) );
                }
                invalidate();
                return true;
        }
        return super.onTouchEvent(event);
    }
}
